import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-09-26
 * Time:20:28
 */
public class MyCallable {
    //创建线程,通过线程来计算1 + 2 + 3 + 4 + 6 + ... + 1000
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //使用Callable来定义一个任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000 ; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //FutureTask存在的意义就是为了让我们能够获取到结果(获取结果的凭证)
        FutureTask<Integer> futureTask = new FutureTask<>(callable);

        //创建线程,来执行上述任务
        //Thread的构造方法,不能直接传callable,还需要一个中间的类
        Thread t = new Thread(futureTask);
        t.start();

        //获取线程的执行结果
        //get方法会阻塞,直到callable方法计算完毕,get会返回
        System.out.println(futureTask.get());
    }
}
